﻿package wibrst.net {
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	/**
	 * ...
	 * @author wibrst@qq.com
	 */
	public class ResCenter extends DataReqCenter{
		
		static private var _i:ResCenter;
		
		static public function get i():ResCenter {
			return _i ||= new ResCenter;
		}
		
		public function sendReq ( sIdRes:String, uLoad:String = "", sIdSeq:String = "",
				bAvoidCache:Boolean = false, bTrace:Boolean = false , bCheckPolicy:Boolean = false
		):void {
			
			this._oDictOK[ sIdRes ] = false;
			
			if ( uLoad == "" ) uLoad = this.queryPath( sIdRes );
			
			if ( bAvoidCache ) {
				var sStampAvoidCache:String = new Date().getTime().toString();
				uLoad += ( uLoad.indexOf("?") == -1 ? "?stamp=" : "&stamp=" ) + sStampAvoidCache;
			}
			
			if(bTrace) trace( this, "sendReq -->: <" +sIdRes + ">", uLoad );
			var resLoader:MarkedResLoader = new MarkedResLoader( sIdRes, sIdSeq );
			resLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, resDataHandler );
			resLoader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			
			var ur:URLRequest = new URLRequest( uLoad );
			
			var loadctx:LoaderContext = new LoaderContext( bCheckPolicy );
			resLoader.load( ur, loadctx );
		}
		
		private function ioErrorHandler( evt:IOErrorEvent ):void {
			var loaderInfo:LoaderInfo = evt.currentTarget as LoaderInfo;
			var resLoader:MarkedResLoader = loaderInfo.loader as MarkedResLoader ;
			
			trace( this, "ioErrorHandler:", evt );
			dispatchEvent( new ERes( ERes.IO_ERROR, resLoader.sId, loaderInfo, resLoader.sIdSeq ) );
			
			resLoader.contentLoaderInfo.removeEventListener( Event.COMPLETE, resDataHandler );
			resLoader.contentLoaderInfo.removeEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			resLoader.unloadAndStop();
		}
		
		private function resDataHandler( evt:Event ):void {
			var loaderInfo:LoaderInfo = evt.currentTarget as LoaderInfo;
			var resLoader:MarkedResLoader = loaderInfo.loader as MarkedResLoader ;
			
			switch( evt.type ) {
			case Event.COMPLETE:		// -+- -+- -+- -+- -+- -+- -+- -+- -+- -+- -+- -+-
				this._oDictOK[ resLoader.sId ] = true;
				
				if ( super._bTraceDetailRec ) {
					trace( this, "resDataHandler <--: <" + resLoader.sId + resLoader.sIdSeq + ">" );
					trace( this, "resDataHandler <-- detail:\n" + loaderInfo );
				}
				super.dispatchEvent( new ERes( ERes.ALL_READY, resLoader.sId, loaderInfo, resLoader.sIdSeq ) );
				
			break;
			}
			
			resLoader.contentLoaderInfo.removeEventListener( Event.COMPLETE, resDataHandler );
			resLoader.contentLoaderInfo.removeEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
			resLoader.unloadAndStop();
			resLoader = null;
		}
		
	}

}